package frog.lazy.framework.core.mybatis.handler;

import frog.lazy.framework.core.base.IBaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(IBaseEnum.class)
public class EnumDefaultTypeHandler<E extends IBaseEnum> extends BaseTypeHandler {
    private final Class<E> type;

    public EnumDefaultTypeHandler(Class<E> type) {
        this.type = type;
    }

    private E valueOf(String value) {
        if(null == value) {
            return null;
        }
        E[] types = type.getEnumConstants();
        for (E ty : types ) {
            if(ty.getValue() == Integer.parseInt(value)) {
                return ty;
            }
        }
       return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        if(o instanceof IBaseEnum) {
            IBaseEnum ibe = (IBaseEnum) o;
            preparedStatement.setInt(i, ibe.getValue());
        }
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String s = resultSet.getString(columnName);
        return valueOf(s);
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String s = resultSet.getString(columnIndex);
        return valueOf(s);
    }

    @Override
    public Object getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String s = callableStatement.getString(columnIndex);
        return valueOf(s);
    }

}
